#import "LightSettingBarController.h"
#import "LightSettingBarView.h"
#import "LightSettingModel.h"
#import <Masonry/Masonry.h>

@interface LightSettingBarController () <UIGestureRecognizerDelegate>
@property (nonatomic, strong) LightSettingBarView *barView;
@end

@implementation LightSettingBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor clearColor];
    self.barView = [[LightSettingBarView alloc] init];
    [self.view addSubview:self.barView];
    [self.barView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
    }];
    self.barView.settingModel = self.settingModel;
    __weak typeof(self) weakSelf = self;
    self.barView.onSettingChanged = ^(LightSettingModel *model) {
        if (weakSelf.onSettingChanged) weakSelf.onSettingChanged(model);
    };
    // 恢复手势加在self.view上
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTapped:)];
    tap.cancelsTouchesInView = NO;
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.barView reloadAll];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UIGestureRecognizer *)touch {
    UIView *touchedView = touch.view;
    if ([touchedView isDescendantOfView:self.barView]) {
        return NO;
    }
    return YES;
}

- (void)backgroundTapped:(UITapGestureRecognizer *)tap {
    CGPoint point = [tap locationInView:self.view];
    if (!CGRectContainsPoint(self.barView.frame, point)) {
        if (self.onRequestHide) {
            self.onRequestHide();
        }
    }
}

- (void)setSettingModel:(LightSettingModel *)settingModel {
    _settingModel = settingModel;
    self.barView.settingModel = settingModel;
}

@end 
